<script lang="ts" setup>
import { ref } from 'vue';

import { dict, useFs } from '@fast-crud/fast-crud';
import { Button } from 'ant-design-vue';

import { SopApiInfoApi } from '#/api/devOperation/sop/sopApiInfo';
import { SopPermGroupPermissionApi } from '#/api/devOperation/sop/sopPermGroupPermission';
import { PermCode } from '#/enums/perm';
import { useMessage } from '#/hooks/web/useMessage';

import { createCrudOptions } from '../data/api-crud';
import { createCrudOptions as selectCreateCrudOptions } from '../data/select-api-crud';

defineOptions({
  name: '接口信息表授权',
  inheritAttrs: false,
});

const permCode = PermCode.devOperation.sop.sopPermGroup;
const groupIdRef = ref<string>('');
const groupNameRef = ref<string>('');
const { crudRef, crudBinding, crudExpose } = useFs({
  createCrudOptions,
  context: { groupIdRef },
});

async function setData(data: any) {
  groupIdRef.value = data.groupId;
  groupNameRef.value = data.groupName;
}

const authorizeRef = ref();
const { createMessage } = useMessage();
async function handleSave(values: string[]) {
  if (!groupIdRef.value) {
    createMessage.error('请先选择分组');
    return;
  }
  await SopPermGroupPermissionApi.save({
    groupId: groupIdRef.value,
    apiIdList: values,
  });
  createMessage.success('授权成功');
  crudExpose.doRefresh();
}

function handleOpen() {
  authorizeRef.value.open(selectCreateCrudOptions);
}
const apiDictRef = dict({
  value: 'id',
  label: 'apiName',
  async getData() {
    return await SopApiInfoApi.query({});
  },
});
defineExpose({ setData, doRefresh: crudExpose.doRefresh });
</script>

<template>
  <FsCrud custom-class="group-api-table" ref="crudRef" v-bind="crudBinding">
    <template #actionbar-right>
      <Button type="text">当前分组： {{ groupNameRef }}</Button>
    </template>
    <template #actionbar-left>
      <FsTableSelect
        ref="authorizeRef"
        v-hasPermission="[permCode.authorize]"
        show-select
        multiple
        :dict="apiDictRef"
        @change="handleSave"
        :create-crud-options="selectCreateCrudOptions"
      >
        <Button type="primary" class="mr-2" @click="handleOpen">授权</Button>
      </FsTableSelect>
    </template>
  </FsCrud>
</template>
